
package com.ywjg.serviceimp;

import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.ywjg.dao.AppGoodDao;
import com.ywjg.dao.GoodCartDao;
import com.ywjg.dao.GoodModelDao;
import com.ywjg.model.GoodCart;
import com.ywjg.model.GoodModel;
import com.ywjg.service.IGoodCartService;
import com.ywjg.utils.Utils;

@Service
public class GoodCartService implements IGoodCartService  {
	@Resource
	GoodCartDao goodCartDao;

	@Resource
	GoodModelDao goodModelDao;

	@Resource
	AppGoodDao appGoodDao;
	
	
	
	/* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#xxx(int)
	 */
	public GoodCart xxx(int id) {
		GoodCart save = goodCartDao.findOne(id);
		return save;
	}
	

    /* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#addGoodToCart(com.ywjg.model.GoodCart)
	 */
    @Transactional
	public GoodCart addGoodToCart(GoodCart goodCart) {
		GoodCart save = goodCartDao.save(goodCart);
		return save;
	}
    /* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#deleteOneGoodFromCart(java.lang.Integer)
	 */
    @Transactional
	public void deleteOneGoodFromCart(Integer id) {
		goodCartDao.delete(id);

	}

    /* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#getUserGoodCart(java.lang.Integer)
	 */
	@Transactional
	public List<GoodCart> getUserGoodCart(Integer user_id) {
		
		getUserCanSaleGoodCart(user_id);
		
		return goodCartDao.findGoodCartByUserId(user_id);
	}

	
	/* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#getUserCanSaleGoodCart(java.lang.Integer)
	 */
	public void getUserCanSaleGoodCart(Integer user_id) {
		List<GoodCart> allUserGood = goodCartDao.findGoodCartByUserId(user_id);
		if (null != allUserGood) {
			for (GoodCart goodCart : allUserGood) {
				GoodModel goodModel = goodModelDao.findOne(goodCart.getGoodModelId());
				Integer goodCartNum = goodCart.getGoodNumber();
				Integer goodModelNum = goodModel.getThisModelNumber();
				Integer goodIsDelete = appGoodDao.findOne(goodCart.getGoodId()).getGoodIsDelete();
				Integer result = (goodCartNum > goodModelNum) ? 0 : 1;
				if (goodIsDelete == 1 || result == 0) {
					goodCart.setCanSale(0);
					upDateUserGoodCart(goodCart);
				}
			}
		}
	}
    /* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#upDateUserGoodCart(com.ywjg.model.GoodCart)
	 */
	public GoodCart upDateUserGoodCart(GoodCart goodCart) {
		GoodCart goodcart = goodCartDao.findOne(goodCart.getId());
		Utils.copyPropertiesIgnoreNull(goodCart, goodcart);
		return goodCartDao.save(goodcart);
	}
    /* (non-Javadoc)
	 * @see com.ywjg.serviceimp.IGoodCartService#findGoodCartByUserId(java.lang.Integer)
	 */
	public List<GoodCart> findGoodCartByUserId(Integer id) {
		// TODO Auto-generated method stub
		return goodCartDao.findGoodCartByUserId(id);
	}

	

	
}
